package com.tdr.comicbook.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by lemingdeng on 2014-06-25.
 */
public class SettingsDataSource {
    //Database fields
    private SQLiteDatabase database;
    private MySQLiteHelper dbHelper;

    public SettingsDataSource(Context context) {dbHelper = MySQLiteHelper.getInstance(context);}

    public void open() { database = dbHelper.getWritableDatabase();}

    public void close() {
        dbHelper.close();
    }

    public synchronized String getValue(String key) {
        String retValue = "";
        this.open();
        Cursor cursor = database.query(MySQLiteHelper.TABLE_SETTINGS, new String[]{MySQLiteHelper.COLUMN_VALUE}, MySQLiteHelper.COLUMN_KEY + "=?", new String[]{key}, null, null, null);
        if (cursor.moveToNext()) {
            retValue = cursor.getString(0);
        }
        cursor.close();
        this.close();
        return retValue;
    }

    public synchronized void setValue(String key, String value) {
        this.open();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MySQLiteHelper.COLUMN_VALUE, value);
        if (0 == database.update(MySQLiteHelper.TABLE_SETTINGS, contentValues, MySQLiteHelper.COLUMN_KEY + "=?", new String[]{key})) {
            contentValues.put(MySQLiteHelper.COLUMN_KEY, key);
            database.insert(MySQLiteHelper.TABLE_SETTINGS, null, contentValues);
        }
        this.close();
    }

}
